import { LoginService, UserService } from '@/api'
import {
  getAccessToken,
  removeAccessToken,
  setAccessToken,
  setUserInfo,
  removeUserInfo,
  removeSelectedKeys,
  removeOpenKeys,
  removeBreadcrumbList,
} from '@/utils/cache/local-storage'

/** 第一个参数是该 store 的唯一 id */
export default defineStore('user', () => {
  const token = ref<string>(getAccessToken())
  const roles: string[] = []
  const permissions: string[] = []
  const avatar = ref<string>('')

  const userInfo = ref<UserEntity.UserInfo | null>(null)

  /** 登录 */
  async function login(loginParams: LoginEntity.LoginParams) {
    const res = await LoginService.login(loginParams)
    console.log('登录data:==>', res)
    const data = res?.data || {}
    const accessToken = data?.accessToken || ''
    token.value = accessToken
    setAccessToken(accessToken)
    return accessToken
  }

  /** 退出登录 */
  async function logout() {
    await LoginService.logout()
    token.value = ''
    userInfo.value = null
    removeAccessToken()
    removeUserInfo()
    removeSelectedKeys()
    removeOpenKeys()
    removeBreadcrumbList()
  }

  async function getUserInfo() {
    const res = await UserService.getUserInfo()
    userInfo.value = res.data
    setUserInfo(res.data)
    avatar.value = res.data?.avatar || ''
    // console.log('用户信息:==>', res)
    return res
  }

  async function register(loginParams: LoginEntity.RegisterParams) {
    const data = await LoginService.register(loginParams)
    console.log('注册用户:==>', data)
  }

  return { token, avatar, userInfo, roles, permissions, login, logout, register, getUserInfo }
})
